package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.MaterialCategoryMapperEx;
import com.jsh.erp.datasource.mappers.MaterialCurrentStockMapperEx;
import com.jsh.erp.datasource.mappers.MaterialMapperEx;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.materialCategory.MaterialCategoryService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.unit.UnitService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

/**
 * @author ji|sheng|hua jshERP
 */
@RestController
@RequestMapping(value = "/material/database")
@Api(tags = {"商品管理"})
public class MaterialDatabaseController {
    private Logger logger = LoggerFactory.getLogger(MaterialDatabaseController.class);
    @Resource
    private UnitService unitService;

    @Resource
    private MaterialCategoryMapperEx materialCategoryMapperEx;
    @Resource
    private MaterialMapperEx materialMapperEx;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Resource
    private MaterialCurrentStockMapperEx materialCurrentStockMapperEx;

    @GetMapping(value = "/purchase-history")
    public String purchaseHistory(@RequestParam String materialId){
        String sql = " select " +
                "dh.id as dh_id ,dh.number, dh.type, dh.sub_type, dh.create_time, dh.organ_id, su.supplier,dh.remark, " +
                "di.id as di_id ,di.material_id, di.oper_number, di.material_unit , di.purchase_decimal, di.wholesale_decimal, di.low_decimal, di.tax_rate,di.discount_rate,di.invoice_type, " +
                "m.id as m_id, m.name as m_name " +
                "from jsh_depot_item as di " +
                "left join jsh_depot_head dh on di.header_id = dh.id " +
                "left join jsh_supplier su on su.id = dh.organ_id " +
                "left join jsh_material m on m.id = di.material_id " +
                "where 1=1 " +
                "and di.material_id = ? " +
                "and dh.sub_type = '采购订单' ";

        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, materialId);
        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("data", maps);
        return returnJson(resultMap, ErpInfo.OK.name, ErpInfo.OK.code);
    }

    //查询
    @PostMapping(value = "/selectDynamic")
    @ApiOperation(value = "动态select更新")
    public String selectDynamic(@RequestBody JSONObject requestParams,
                                        HttpServletRequest request, HttpServletResponse response) throws Exception{
        String field = requestParams.getString("field");
        JSONObject queryParam = requestParams.getJSONObject("queryParam");

        StringBuilder conditions = new StringBuilder();
        for (String key : queryParam.keySet()){
            if ( key.equals("categoryId") && StringUtils.isNoneBlank(queryParam.getString("categoryId")) ){
                String conditionStr = "and category_id = "+queryParam.getString("categoryId")+" ";
                conditions.append(conditionStr);
            }else{
                JSONArray values = queryParam.getJSONArray(key);
                if ( values != null && values.size()>0){
                    List<String> conditionItems = Lists.newArrayList();
                    for (int i = 0; i < values.size(); i++) {
                        conditionItems.add("'"+values.getString(i)+"'");
                    }

                    String conditionValue = StringUtils.joinWith(",", conditionItems);
                    conditionValue = conditionValue.replaceAll("\\[","").replaceAll("]","");
                    String conditionStr = "and "+key+" in ("+conditionValue+") ";
                    conditions.append(conditionStr);

                }
            }
        }

        String sql = " select "+field+" as f from full_material_view where 1=1 "+conditions.toString() +" group by "+field;
        System.out.println("sql -->  "+sql);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);

        JSONArray array = new JSONArray();
        for (Map<String,Object> map : maps){
            if ( map.get("f") == null){
                continue;
            }
            array.add(new JSONObject().fluentPut("label",map.get("f").toString()).fluentPut("value",map.get("f").toString()));
        }

        Map<String,Object> result = Maps.newHashMap();
        result.put("options", array);
        return returnJson(result,ErpInfo.OK.name, ErpInfo.OK.code);
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "获取信息列表")
    public String getList(@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
                          @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
                          @RequestParam(value = Constants.SEARCH, required = false) String search,
                          HttpServletRequest request)throws Exception {
        Map<String, String> parameterMap = ParamUtils.requestToMap(request);
        parameterMap.put(Constants.SEARCH, search);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        if (pageSize != null && pageSize <= 0) {
            pageSize = 10;
        }
        String offset = ParamUtils.getPageOffset(currentPage, pageSize);
        if (StringUtil.isNotEmpty(offset)) {
            parameterMap.put(Constants.OFFSET, offset);
        }
        List<?> list = select(parameterMap);
        if (list != null) {
            objectMap.put("total", counts( parameterMap));
            objectMap.put("rows", list);
            return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "查找不到数据", ErpInfo.OK.code);
        }
    }

    public List<?> select(Map<String, String> map)throws Exception {
        return getMaterialList(map);
    }

    private List<String> getParams(JSONObject search, String key){
        if ( search.getJSONArray(key) == null ){
            return new ArrayList<>();
        }else{
            return search.getJSONArray(key).toJavaList(String.class);
        }
    }

    private List<?> getMaterialList(Map<String, String> map) throws Exception{
        String search = map.get(Constants.SEARCH);

        JSONObject searchJson = JSONObject.parseObject(search);
        List<String> names = getParams(searchJson,"name");
        List<String> mfrs = getParams(searchJson,"mfrs");
        List<String> model = getParams(searchJson,"model");
        List<String> otherField1 = getParams(searchJson,"otherField1");
        List<String> caizhi = getParams(searchJson,"caizhi");
        List<String> biaozhun = getParams(searchJson,"biaozhun");
        List<String> lianjie = getParams(searchJson,"lianjie");
        List<String> paoguangdu = getParams(searchJson,"paoguangdu");
        List<String> mopian = getParams(searchJson,"mopian");
        List<String> changdu = getParams(searchJson,"changdu");
        List<String> otherField2 = getParams(searchJson,"otherField2");
        List<String> otherField3 = getParams(searchJson,"otherField3");
        List<String> standard = getParams(searchJson,"standard");


        List<MaterialVo4Unit> materialVo4UnitList = selectByFullParamMaterialIn(
                        StringUtil.getInfo(search,"categoryId"),
                names,mfrs,model,otherField1,caizhi,biaozhun,lianjie,paoguangdu,
                mopian,changdu,otherField2,otherField3,standard,StringUtil.getInfo(search, "enable"),
                        QueryUtils.offset(map), QueryUtils.rows(map));

        return materialVo4UnitList;
    }

    public Long counts(Map<String, String> map)throws Exception {
        String search = map.get(Constants.SEARCH);
        JSONObject searchJson = JSONObject.parseObject(search);
        List<String> names = getParams(searchJson,"name");
        List<String> mfrs = getParams(searchJson,"mfrs");
        List<String> model = getParams(searchJson,"model");
        List<String> otherField1 = getParams(searchJson,"otherField1");
        List<String> caizhi = getParams(searchJson,"caizhi");
        List<String> biaozhun = getParams(searchJson,"biaozhun");
        List<String> lianjie = getParams(searchJson,"lianjie");
        List<String> paoguangdu = getParams(searchJson,"paoguangdu");
        List<String> mopian = getParams(searchJson,"mopian");
        List<String> changdu = getParams(searchJson,"changdu");
        List<String> otherField2 = getParams(searchJson,"otherField2");
        List<String> otherField3 = getParams(searchJson,"otherField3");
        List<String> standard = getParams(searchJson,"standard");


        return countsByFullParamMaterialIn(
                StringUtil.getInfo(search,"categoryId"),
                names,mfrs,model,otherField1,caizhi,biaozhun,lianjie,paoguangdu,
                mopian,changdu,otherField2,otherField3,standard,StringUtil.getInfo(search, "enable"));

    }

    public List<MaterialVo4Unit> selectByFullParamMaterialIn(String categoryId,List<String> name, List<String> mfrs,
                                                             List<String> model,List<String> otherField1,List<String> caizhi,List<String> biaozhun,
                                                             List<String> lianjie,List<String> paoguangdu,List<String> mopian,List<String> changdu,
                                                             List<String> otherField2,List<String> otherField3,List<String> standard,String enabled, int offset, int rows)
            throws Exception{
        String[] mpArr = new String[]{};

        List<MaterialVo4Unit> resList = new ArrayList<>();
        List<MaterialVo4Unit> list =null;
        try{
            List<Long> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = getListByParentId(Long.parseLong(categoryId));
            }
            list = materialMapperEx.selectByFullParamMaterialIn(idList,name,mfrs,model,otherField1,caizhi,biaozhun,lianjie,paoguangdu,
                    mopian,changdu,otherField2,otherField3,standard,enabled,offset,rows);

            if (null != list && list.size()>0) {
                Map<Long,BigDecimal> currentStockMap = getCurrentStockMapByMaterialList(list);
                for (MaterialVo4Unit m : list) {
                    m.setMaterialOther(getMaterialOtherByParam(mpArr, m));
                    m.setStock(currentStockMap.get(m.getId())!=null? currentStockMap.get(m.getId()): BigDecimal.ZERO);
                    m.setBigUnitStock(getBigUnitStock(m.getStock(), m.getUnitId()));
                    resList.add(m);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            JshException.readFail(logger, e);
        }
        return resList;
    }

    public Long countsByFullParamMaterialIn(String categoryId,List<String> name, List<String> mfrs,
                                            List<String> model,List<String> otherField1,List<String> caizhi,List<String> biaozhun,
                                            List<String> lianjie,List<String> paoguangdu,List<String> mopian,List<String> changdu,
                                            List<String> otherField2,List<String> otherField3,List<String> standard, String enabled)throws Exception {
        Long result =null;
        try{
            List<Long> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = getListByParentId(Long.parseLong(categoryId));
            }
            result= materialMapperEx.countsByFullParamMaterialIn(idList,name,mfrs,model,otherField1,caizhi,biaozhun,lianjie,paoguangdu,
                    mopian,changdu,otherField2,otherField3,standard,enabled);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Long> getListByParentId(Long parentId) {
        List<Long> idList = new ArrayList<Long>();
        List<MaterialCategory> list = materialCategoryMapperEx.getListByParentId(parentId);
        idList.add(parentId);
        if(list!=null && list.size()>0) {
            getIdListByParentId(idList, parentId);
        }
        return idList;
    }

    public List<Long> getIdListByParentId(List<Long> idList, Long parentId){
        List<MaterialCategory> list = materialCategoryMapperEx.getListByParentId(parentId);
        if(list!=null && list.size()>0) {
            for(MaterialCategory mc : list){
                idList.add(mc.getId());
                getIdListByParentId(idList, mc.getId());
            }
        }
        return idList;
    }

    /**
     * 根据商品列表获取当前库存Map
     * @param list
     * @return
     */
    public Map<Long,BigDecimal> getCurrentStockMapByMaterialList(List<MaterialVo4Unit> list) {
        Map<Long,BigDecimal> map = new HashMap<>();
        List<Long> materialIdList = new ArrayList<>();
        for(MaterialVo4Unit materialVo4Unit: list) {
            materialIdList.add(materialVo4Unit.getId());
        }
        List<MaterialCurrentStock> mcsList = materialCurrentStockMapperEx.getCurrentStockMapByIdList(materialIdList);
        for(MaterialCurrentStock materialCurrentStock: mcsList) {
            map.put(materialCurrentStock.getMaterialId(), materialCurrentStock.getCurrentNumber());
        }
        return map;
    }

    public String getMaterialOtherByParam(String[] mpArr, MaterialVo4Unit m) {
        String materialOther = "";
        for (int i = 0; i < mpArr.length; i++) {
            if (mpArr[i].equals("制造商")) {
                materialOther = materialOther + ((m.getMfrs() == null || m.getMfrs().equals("")) ? "" : "(" + m.getMfrs() + ")");
            }
            if (mpArr[i].equals("自定义1")) {
                materialOther = materialOther + ((m.getOtherField1() == null || m.getOtherField1().equals("")) ? "" : "(" + m.getOtherField1() + ")");
            }
            if (mpArr[i].equals("自定义2")) {
                materialOther = materialOther + ((m.getOtherField2() == null || m.getOtherField2().equals("")) ? "" : "(" + m.getOtherField2() + ")");
            }
            if (mpArr[i].equals("自定义3")) {
                materialOther = materialOther + ((m.getOtherField3() == null || m.getOtherField3().equals("")) ? "" : "(" + m.getOtherField3() + ")");
            }
        }
        return materialOther;
    }

    public String getBigUnitStock(BigDecimal stock, Long unitId) throws Exception {
        String bigUnitStock = "";
        if(null!= unitId) {
            Unit unit = unitService.getUnit(unitId);
            if(unit.getRatio()!=null && unit.getRatio().compareTo(BigDecimal.ZERO)!=0 && stock!=null) {
                bigUnitStock = stock.divide(unit.getRatio(),2,BigDecimal.ROUND_HALF_UP) + unit.getOtherUnit();
            }
        }
        return bigUnitStock;
    }
}
